import { defineStore } from 'pinia';
import axios from 'axios';

export const useUserStore = defineStore('user', {
  state: () => ({
    token: localStorage.getItem('admin-token') || '',
    username: '',
    name: '',
    avatar: '',
    roles: []
  }),
  
  getters: {
    isLoggedIn: (state) => !!state.token
  },
  
  actions: {
    // 登录
    async login(username, password) {
      try {
        const response = await axios.post('/admin/login', { username, password });
        
        if (response.data.code === 0) {
          const token = response.data.data.token;
          localStorage.setItem('admin-token', token);
          this.token = token;
          
          // 获取用户信息
          await this.getUserInfo();
          
          return Promise.resolve(response.data);
        } else {
          return Promise.reject(response.data.message || '登录失败');
        }
      } catch (error) {
        return Promise.reject(error.response?.data?.message || '网络错误');
      }
    },
    
    // 获取用户信息
    async getUserInfo() {
      try {
        const response = await axios.get('/admin/user/info', {
          headers: { 'Authorization': 'Bearer ' + this.token }
        });
        
        if (response.data.code === 0) {
          const data = response.data.data;
          this.username = data.username;
          this.name = data.name;
          this.avatar = data.avatar;
          this.roles = data.roles;
          
          return Promise.resolve(data);
        } else {
          return Promise.reject(response.data.message || '获取用户信息失败');
        }
      } catch (error) {
        return Promise.reject(error.response?.data?.message || '网络错误');
      }
    },
    
    // 登出
    async logout() {
      try {
        await axios.post('/admin/logout');
      } catch (error) {
        console.error('登出请求失败:', error);
      } finally {
        // 无论请求成功与否，都清除本地存储的token和状态
        localStorage.removeItem('admin-token');
        this.token = '';
        this.username = '';
        this.name = '';
        this.avatar = '';
        this.roles = [];
      }
    }
  }
}); 